<template>
    <div id="client">
        <div class="client-top" style="">
            客户：
            <el-input style="width: 200px; margin-left: 0px; margin-right: 20px" placeholder="请输入客户编号"
                v-model="receipt.customerName" clearable disabled>
            </el-input>
            <el-button style="margin-left: -20px; margin-right: 10px" @click="dialogFormVisible = true">...</el-button>

            总欠款：
            <el-input style="width: 80px; margin-left: 0px; margin-right: 20px" placeholder="" clearable disabled>
            </el-input>
            业务员：
            <el-select placeholder="业务员" style="width: 100px">
                <el-option>
                </el-option>
            </el-select>

            <span class="demonstration" style="margin-left: 20px">单据日期:</span>
            <el-date-picker v-model="selectedDate" align="right" type="date" placeholder="选择日期"
                :picker-options="pickerOptions" @change="handleDateChange" style="margin-left: 10px;"></el-date-picker>
            <i class="el-icon-paperclip" style="color: blue; margin-left: 40px"></i>
            <sapn style="color: blue">上传附件</sapn>
            <span style="margin-left: 10px">单据编号:</span>
            <el-input v-model="receipt.receiveOrderId" style="width: 120px; margin-left: 10px; margin-right: 20px"
                placeholder="" clearable disabled>
            </el-input>

            <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                    <i class="el-icon-edit"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item, index) in rules" :key="index" :command="item">{{ item.example
                        }}</el-dropdown-item>

                </el-dropdown-menu>
            </el-dropdown>
        </div>
        <hr style="margin-top: 10px">
        <div style="margin-top: 10px;float: right">
            <el-button type="success" @click="check()" :disabled="isCheckDisabled">审核</el-button><el-button
                type="warning" @click="returnCheck()" :disabled="isReturnCheckDisabled">反审核</el-button>
        </div>
        <div style="clear: both;"></div>
        <div class="client-content" style="margin-top: 10px">
            <el-table height="180px" :data="tableData" border style="width: 100%;font-size: 13px;">
                <el-table-column fixed prop="" label="" width="50">
                    <i class="el-icon-circle-plus-outline" style="margin-left: 8px;" @click="addRow()"></i>
                    <br>
                    <i class="el-icon-remove-outline" style="margin-left: 8px;"></i>
                </el-table-column>
                <el-table-column fixed prop="account" label="结算账户" width="150">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.account" placeholder="结算账户" style="width: 100px;">
                            <el-option v-for="item in accounts" :key="item.accountId" :label="item.accountName"
                                :value="item.accountId">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="money" label="收款金额" width="140">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.money" style="width: 100px;margin-left: 10px;margin-right: 20px;"
                            placeholder="收款金额" clearable @input="checkNum()" disabled>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="clearMethod" label="结算方式" width="140">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.clearMethod" placeholder="结算方式" style="width: 110px;">
                            <el-option v-for="item in clearMethods" :key="item.clearId" :label="item.clearName"
                                :value="item.clearId">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="clearNum" label="结算号" width="140">
                    <el-input style="width: 100px;margin-left: 10px;margin-right: 20px;" placeholder="结算号" clearable
                        disabled>
                    </el-input>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="300">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remark" style="width: 250px;margin-left: 10px;margin-right: 20px;"
                            placeholder="备注" clearable disabled>
                        </el-input>
                    </template>
                </el-table-column>

            </el-table>

            <div style="margin-top: 10px">
                <div style="float: right">
                    <el-button slot="reference" @click="chooseInitForm">选择源单</el-button>

                    <el-dialog top="20px" title="" :visible.sync="choose">
                        <ShouldForm :customerNum="customerCode" :choose="choose" ref="shouldForm" />
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="choose = false">取 消</el-button>
                            <el-button type="primary" @click="yesForm()">确 定</el-button>
                        </div>
                    </el-dialog>
                    <el-button @click="changeMoney">自动核销</el-button>
                </div>

                <el-table height="180px" :data="formDate" border style="width: 100%; font-size: 13px">
                    <el-table-column fixed prop="" label="" width="50">
                        <i class="el-icon-circle-plus-outline" style="margin-left: 8px;" @click="addRow1()"></i>
                        <br>
                        <i class="el-icon-remove-outline" style="margin-left: 8px;"></i>
                    </el-table-column>
                    <el-table-column prop="documentNum" label="源单编号" width="150">
                    </el-table-column>

                    <el-table-column prop="documentDate" label="单据日期" width="120">
                    </el-table-column>
                    <el-table-column prop="received" label="单据金额" width="120">
                    </el-table-column>
                    <el-table-column prop="writtenOffMoney" label="已核销金额" width="120">
                    </el-table-column>
                    <el-table-column prop="noMoney" label="未核销金额" width="120">
                    </el-table-column>
                    <el-table-column prop="nowMoney" label="本次核销金额" width="130">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.nowMoney"
                                style="width: 100px;margin-left: 10px;margin-right: 20px;" placeholder="收款金额" clearable
                                disabled>
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="zip" label="单据备注" width="120">
                    </el-table-column>
                </el-table>
                <el-input type="textarea" :rows="2" placeholder="暂无备注信息" v-model="receipt.remark"
                    style="width: 100%; line-height: 20px" disabled>
                </el-input>
                <div style="float: right; margin-right: 20px; margin-top: 10px">
                    本次预收款：
                    <el-input v-model="getMoney" style="width: 200px; margin-left: 10px; margin-right: 20px"
                        placeholder="本次预收款" clearable disabled>
                    </el-input>
                    <el-button @click="goto('RceiptHistory')">历史单据</el-button><el-button>操作日志</el-button>
                </div>
            </div>
            <div></div>
        </div>
        <div style="height: 20px; clear: both"></div>
        <el-dialog top="20px" title="选择客户" :visible.sync="dialogFormVisible">
            <ClientChoose ref="clientChoose" />
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible1()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
import ClientChoose from '../public_com/ClientChoose.vue';
import ShouldForm from './ShouldForm.vue';


export default {
    components: {
        ClientChoose,
        ShouldForm,
    },
    data() {
        return {
            taskId: "",
            isCheckDisabled: false, // 解除禁用审核按钮
            isReturnCheckDisabled: true,
            preMoney: "",
            delMoney: 0,
            dialogFormVisible: false,
            choose: false,
            id: "",
            employees: "",
            customerCode: "",
            receipt: {
                aName: "",
                aid: "",
                checkId: "",
                customerId: "",
                customerCode: "",
                customerName: "",
                customerType: "",
                doId: 1,
                id: "",
                initOrderId: "",
                isWriteOff: 2,
                orderDate: "",
                orderType: 1,
                payAccount: "",
                payoutMoney: "",
                payoutType: "",
                preMoney: "",
                receiveOrderId: "",
                writeoffMoney: "",
                yid: "",
                checkStatus: ""
            },
            pageInfo: "",
            typeList: "",
            typeId: "",
            clientCode: "",
            clearMethods: "",
            accounts: "",
            rules: "",
            command: "",
            selectedDate: '',
            documentDate: "",
            clientName: "",
            pickerOptions: {},
            tableData: [{
                account: '',
                money: "",
                clearMethod: '',
                clearNum: '',
                remark: '',
            }],
            formDate: [
                {
                    documentNum: "",
                    documentDate: "",
                    received: "",
                    writtenOffMoney: 0,
                    remark: "",
                    noMoney: 0,
                    nowMoney: 0,

                },

            ],
        };
    },
    watch: {
        // 监听每一行的money变化
        tableData: {
            handler(newValue) {
                let totalMoney = 0;
                newValue.forEach(row => {
                    const money = parseFloat(row.money) || 0;
                    totalMoney += money;
                });
                this.receipt.preMoney = totalMoney;
            }, deep: true
        },
        // 监听每一行的nowMoney变化
        formDate: {
            handler(newValue) {
                let totalNowMoney = 0;
                newValue.forEach(row => {
                    const nowMoney = parseFloat(row.nowMoney) || 0;
                    totalNowMoney -= nowMoney;
                });
                this.delMoney = totalNowMoney;
            }, deep: true
        }
    },
    computed: {
        getMoney() {
            this.preMoney = this.receipt.preMoney + this.delMoney
            return this.preMoney
        },
    },
    methods: {
        gitR: function () {

        },
        returnCheck: function () {
            this.isCheckDisabled = false; // 解除禁用审核按钮
            this.isReturnCheckDisabled = true;
            const formData = new FormData();
            formData.append('shouldForm', JSON.stringify(this.formDate))
            formData.append('list', JSON.stringify(this.tableData));
            formData.append('receiptForm', JSON.stringify(this.receipt))
            this.axios.post(
                "/cash/check/returnCheckNum",
                formData,
                {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }
            ).then(rs => {
                console.log(rs)
                if (rs.data.code === 200) {
                    alert("保存成功")
                    this.selectById()
                    this.selectByReceiptId()
                    this.selectRs()
                } else {
                    alert("保存失败")
                }
            })
        },
        changeMoney: function () {
            let money = 0.0;
            let all = 0.0;

            // 计算tableData中的总金额
            this.tableData.forEach(item => {
                money += parseFloat(item.money) || 0.0;
            });

            // 计算formDate中的未核销总金额
            this.formDate.forEach(item => {
                all += parseFloat(item.noMoney) || 0.0;
            });

            for (let i = 0; i < this.formDate.length; i++) {
                if (this.formDate[i].noMoney > money) {
                    this.formDate[i].nowMoney = money;
                    // 将其他对象的nowMoney设为0
                    this.formDate.forEach((item, index) => {
                        if (i !== index) {
                            item.nowMoney = 0.0;
                        }
                    });
                    return true;
                }

                if (all >= money) {
                    let wMoney = parseFloat(this.formDate[i].noMoney) || 0.0;
                    if (wMoney < money) {
                        this.formDate[i].nowMoney = wMoney;
                    } else {
                        this.formDate[i].nowMoney = money;
                        return true;
                    }
                }
            }
        },
        check: function () {



            const reg = /^([1-9]\d*(\.\d{1,2})?|0\.\d{1,2})$/
            if (this.receipt.customerId === "") {
                alert("请选择客户")
                return
            }
            if (this.receipt.orderDate === "") {
                alert("请选择日期")
                return
            }
            if (this.receipt.receiveOrderId === "") {
                alert("请选择单据编号不能为空")
                return
            }

            for (const contact of this.tableData) {
                if (contact.account === "") {
                    alert("请选择结算账户")
                    return
                }
                if (contact.money === "") {
                    alert("请填写收款金额")
                    return
                }
                if (isNaN(contact.money)) {
                    alert("收款金额必须为数字")
                    return
                }
                if (!reg.test(contact.money)) {
                    alert("收款金额不符合规范")
                    return
                }
            }
            this.axios({
                url: "/cash/check/competePay",
                params: {
                    taskId: this.taskId
                }
            }
            ).then(rs => {
                console.log(rs)
                if (rs.data.code === 200) {
                    alert("保存成功")
                    this.isCheckDisabled = true; // 禁用审核按钮
                    this.isReturnCheckDisabled = false; // 解除禁用反审核按钮
                    this.selectById()
                    this.selectByReceiptId()
                    this.selectRs()
                } else {
                    alert("保存失败")
                }
            })
        },
        selectRs: function () {
            this.axios({
                url: "/cash/rSDetail/selectByReceipt",
                params: {
                    receiptId: this.receipt.id
                }
            }).then(rs => {
                console.log(rs)
                this.formDate = rs.data.list
                console.log(rs.data.list)
            })
        },

        git: function () {
            let formMoney = 0
            let writeMoney = 0
            this.tableData.forEach(item => {
                formMoney += item.money
            })
            this.receipt.writeoffMoney = formMoney
            this.formDate.forEach(item => {
                writeMoney += item.nowMoney
            })

            if (formMoney !== writeMoney) {
                alert("本次核销金额")
            }
        },
        addRow1: function () {
            this.formDate.push(
                {
                    documentNum: "",
                    documentDate: "",
                    received: "",
                    writtenOffMoney: 0,
                    remark: "",
                    noMoney: 0,
                    nowMoney: 0,
                }
            )
        },
        yesForm() {
            this.choose = false
            // this.goodsList = 
            // console.log(this.goodsList)
            //遍历商品列表
            this.formDate = this.$refs.shouldForm.selectionList
            console.log(this.$refs.shouldForm.selectionList)
        },
        // checkNum: function () {
        //   const reg = /^([1-9]\d*(\.\d{1,2})?|0\.\d{1,2})$/
        //   for (const contact of this.tableData) {
        //     if (isNaN(contact.money)) {
        //       alert("请输入数字")
        //       contact.money
        //       return
        //     }
        //     if (!reg.test(contact.money)) {
        //       product.num = 1
        //     }
        //   }
        // },
        chooseInitForm: function () {
            if (this.receipt.customerName === "") {
                alert("请选择客户")
            } else {
                this.choose = true
            }
        },
        selectByReceiptId: function () {
            console.log(this.receipt.id)

            this.axios({
                url: "/cash/rDetail/selectByReceipt",
                params: {
                    receiptId: this.receipt.id
                }
            }).then(rs => {
                console.log(rs)
                this.tableData = rs.data.list
            })
        },
        dialogFormVisible1: function () {
            this.dialogFormVisible = false
            const id = this.$refs.clientChoose.clientCode
            this.receipt.customerId = id
            this.customerCode = this.$refs.clientChoose.clientCode
            // console.log(this.$refs.clientChoose.clientName)
            this.receipt.customerCode = this.$refs.clientChoose.clientId
            // console.log(this.receipt.customerCode)
            this.receipt.customerName = this.$refs.clientChoose.clientName
            // console.log(this.receipt.customerId)
        },
        handleDateChange(value) {
            // value 即为选中的日期值
            console.log('选中的日期是：', value);
            this.receipt.orderDate = value
            // 在这里可以执行更多的逻辑，比如更新数据、调用 API 等
        },
        handleCommand(command) {
            console.log('选中的值是：', command);
            this.receipt.receiveOrderId = command.example
            // 这里可以执行更多的逻辑，比如更新数据、调用 API 等
        },
        getRules: function () {
            axios({
                url: "/info/receipt/selectAll",
            }).then(rs => {
                console.log(rs)
                this.rules = rs.data.list
            })
        },
        update: function () {

            this.receipt.preMoney = this.preMoney
            let formMoney = 0
            // let writeMoney = 0
            this.formDate.forEach(item => {
                const writtenOffMoney = parseFloat(item.nowMoney) || 0;
                formMoney += writtenOffMoney
            })
            this.receipt.writeoffMoney = formMoney
            // console.log(this.receipt.writeoffMoney)
            // console.log(this.receipt.preMoney)
            // return
            const reg = /^([1-9]\d*(\.\d{1,2})?|0\.\d{1,2})$/
            if (this.receipt.customerId === "") {
                alert("请选择客户")
                return
            }
            if (this.receipt.orderDate === "") {
                alert("请选择日期")
                return
            }
            if (this.receipt.receiveOrderId === "") {
                alert("请选择单据编号不能为空")
                return
            }
            for (const contact of this.tableData) {
                if (contact.account === "") {
                    alert("请选择结算账户")
                    return
                }
                if (contact.money === "") {
                    alert("请填写收款金额")
                    return
                }
                if (isNaN(contact.money)) {
                    alert("收款金额必须为数字")
                    contact.money
                    return
                }
                if (!reg.test(contact.money)) {
                    alert("收款金额不符合规范")
                    return
                }
            }
            console.log(this.tableData)
            console.log(this.receipt)
            // alert(this.receipt.writeoffMoney)
            // return
            const formData = new FormData();
            formData.append('shouldForm', JSON.stringify(this.formDate))
            formData.append('receiptForm', JSON.stringify(this.receipt))
            formData.append('list', JSON.stringify(this.tableData));
            this.axios.post(
                "/cash/receipt/update",
                formData,
                {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }
            ).then(rs => {
                console.log(rs)
                if (rs.data.code === 200) {
                    alert("保存成功")
                    this.selectById()
                    this.selectByReceiptId()
                    this.selectRs()
                } else {
                    alert("保存失败")
                }
            })
        },
        getAccounts: function () {
            this.axios({
                url: "/info/account/selectAll",
                params: {

                }
            }).then(rs => {
                console.log(rs)
                this.accounts = rs.data.accounts
            })
        },
        addRow: function () {
            this.tableData.push({
                account: '',
                money: '',
                clearMethod: '',
                clearNum: '',
                remark: '',
            })
        },
        getClearMethod: function () {
            axios({
                url: "/info/clear/selectAll",
            }).then(rs => {

                this.clearMethods = rs.data.list
                console.log(this.clearMethods)
            })
        },
        handleCurrentChange(val) {
            this.getClients(val, 5)
        },

        goto(to) {
            this.$router.push(to)
        },
        selectById: function () {
            // alert(this.id)
            if (this.id == null) {
                return
            }
            axios({
                url: "/cash/receipt/selectById",
                params: {
                    id: this.receipt.id
                }
            }).then(rs => {
                console.log(rs)
                this.receipt = rs.data.receipt
                if (rs.data.receipt.checkStatus === 1) {
                    this.isCheckDisabled = true
                    this.isReturnCheckDisabled = false
                }
            })
        },
        getEmployees: function () {
            this.axios({
                url: "/info/employee/listAll",
            }).then(rs => {
                console.log(rs)
                this.employees = rs.data.list
            })
        },
        selectByCode: function (code) {
            // alert(this.id)
            if (this.id == null) {
                return
            }
            this.axios({
                url: "/cash/receipt/selectByCode",
                params: {
                    code: code
                }
            }).then(rs => {
                console.log(rs)
                this.receipt = rs.data.receipt
                this.selectByReceiptId()
                this.selectRs()
                if (rs.data.receipt.checkStatus === 2) {
                    this.isCheckDisabled = true
                    this.isReturnCheckDisabled = false
                } else {
                    this.isCheckDisabled = false
                    this.isReturnCheckDisabled = true
                }
                // window.location.reload()
            })
        },
    },

    created: function () {
        if (this.$route.query.id != '' && this.$route.query.id != null) {
            this.id = this.$route.query.id
            this.receipt.id = this.$route.query.id
            this.selectById()
        }
        if (this.$route.query.billCode != '' && this.$route.query.billCode != null) {
            const headerCode = this.$route.query.billCode
            this.taskId = this.$route.query.taskId
            this.selectByCode(headerCode)
        }
        // alert(this.id)
        this.getClearMethod()
        this.getAccounts()
        this.getRules()

    }
};
</script>

<style scoped>
.el-button el-button--default el-popover__reference {
    margin-right: 20px;
}

tr {
    border: 1px solid black;
}

.td {
    line-height: 10px;
}
</style>